package cn.jilian.sys.web;

import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.fasterxml.jackson.databind.ObjectMapper;

import cn.jilian.common.domain.R;
import cn.jilian.common.dto.FilterPageSortQuery;
import cn.jilian.common.dto.PageResult;
import cn.jilian.common.util.MapUtil;
import cn.jilian.entity.Role;
import cn.jilian.sys.service.RoleService;
import cn.jilian.sys.util.SessionUtil;

@Controller
@RequestMapping("/role")
public class RoleController {

	@Autowired
	private RoleService roleService;
	
	@Autowired
	private ObjectMapper objectMapper;
	
	@GetMapping("/mgr.html")
	public ModelAndView mgr() {
		ModelAndView mv=new ModelAndView("gui/tab");
		mv.addObject("jsfile", "sys.role_mgr");
		mv.addObject("title", "角色管理");
		return mv;
	}
	
	@GetMapping("")
	@ResponseBody
	public PageResult<Role> query(@RequestParam Map<String,Object> params,HttpSession session){
		long unid=SessionUtil.getUnitId(session);
		Map<String,Object> data=MapUtil.expand(params);
		MapUtil.putExtendedValue(data, "filter.unid", unid);
		FilterPageSortQuery query=objectMapper.convertValue(data, FilterPageSortQuery.class);
		return roleService.list(query);
	}
	
	@RequiresPermissions("system:role:add")
	@PutMapping("")
	public R addRole(@RequestParam Role role) {
		try {
			roleService.addRole(role);
			return R.ok;
		}catch(Exception e) {
			e.printStackTrace();
			return R.fail;
		}
	}
	
//	@RequiresPermissions("system:role:update")
	@PostMapping("")
	public R updateRole(@RequestParam Role role) {
		try {
			roleService.updateRole(role);
			return R.ok;
		}catch(Exception e) {
			e.printStackTrace();
			return R.fail;
		}
	}
	
	@DeleteMapping("/{id}")
	public R deleteRole(@PathVariable Long id) {
		try {
			roleService.delete(id);
			return R.ok;
		}catch(Exception e) {
			e.printStackTrace();
			return R.fail;
		}
	}
}
